package com.hui.stock.face.impl;

import com.hui.stock.face.UserCacheFace;
import com.hui.stock.mapper.SysRoleMapper;
import com.hui.stock.mapper.SysRolePermissionMapper;
import com.hui.stock.pojo.domain.MenuDomain;
import com.hui.stock.pojo.entity.SysPermission;
import com.hui.stock.pojo.entity.SysRole;
import com.hui.stock.utils.UserRolePermissionUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: ymh
 * @date: 2025/1/14 16:28
 * @description:
 */
@Component
public class UserCacheFaceImpl implements UserCacheFace {
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private SysRolePermissionMapper sysRolePermissionMapper;

    @Cacheable(cacheNames = "user",key = "#root.methodName + #userId")
    @Override
    public List<SysPermission> getUserPermissions(Long userId) {
        //1 获取用户角色id
        List<Long> roleIds = sysRoleMapper.getRoleIds(userId);
        //2 根据用户角色id获取菜单列表
        List<SysPermission> permissions = sysRolePermissionMapper.getPermissionList(roleIds);
        return permissions;
    }

    @Cacheable(cacheNames = "user",key = "#root.methodName + #userId")
    @Override
    public List<String> getUserGrantedAuthorityString(Long userId) {
        List<SysPermission> permissions = this.getUserPermissions(userId);
        //获取SpringSecurity的权限标识ROLE_角色名称
        List<String> pers = permissions.stream()
                .map(SysPermission::getPerms)
                .filter(StringUtils::isNotBlank)
                .collect(Collectors.toList());
        List<Long> roleIds = sysRoleMapper.getRoleIds(userId);
        List<SysRole> sysRoles = sysRoleMapper.batchSelectByPrimaryKey(roleIds);
        pers.addAll(sysRoles.stream()
                .map(per->"ROLE_"+per.getName())
                .collect(Collectors.toList()));

        return pers;
    }

    @Override
    public List<String> getUserMenu(Long userId) {
        return null;
    }
}
